package cc.rengu.igas.cops.core.service.trans.unionpay;

import cc.rengu.igas.channel.upqc.facade.bean.CouponInfoBean;
import cc.rengu.igas.channel.upqc.facade.bean.PayeeInfoBean;
import cc.rengu.igas.channel.upqc.facade.bean.PayerInfo;
import cc.rengu.igas.channel.upqc.facade.bean.RiskInfoBean;
import cc.rengu.igas.channel.upqc.facade.request.B2COrderPayRequest;
import cc.rengu.igas.channel.upqc.facade.request.B2CQueryCouponRequest;
import cc.rengu.igas.channel.upqc.facade.response.B2COrderPayResponse;
import cc.rengu.igas.channel.upqc.facade.response.B2CQueryCouponResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.cops.common.constant.CopsParamConstant;
import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.facade.bean.CouponInfo;
import cc.rengu.igas.cops.facade.bean.RiskInfo;
import cc.rengu.igas.cops.facade.request.BankB2cOrderPayRequest;
import cc.rengu.igas.cops.facade.response.BankB2cOrderPayResponse;
import cc.rengu.igas.share.common.enums.UserPayAuthTypeEnum;
import cc.rengu.igas.share.core.model.UserInfo;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.base.BizBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.RiskMonitorInfo;
import cc.rengu.oltp.service.realize.*;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.SmsServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 主扫---付款
 * 手机【ESB】—>支付—>通道—>银联（同步接口，银联扣款后返回结果）
 * <p>
 * 订单表字段：
 * remark1：二维码类型
 * remark2：收款方信息JSON
 * discount_info：优惠信息json list
 * front_seq_num前端流水号：付款凭证号
 *
 * @author panky
 * @version 1.0.0 创建时间：2020.06.23
 */
public class BankB2cOrderPayService extends BizBaseService implements TransCustomImpl {

    @Override
    protected Object beforeBizProcess() throws Exception {
        BankB2cOrderPayRequest bankB2cOrderPayRequest = new BankB2cOrderPayRequest();
        ConvertUtil.convertOutput(bankB2cOrderPayRequest);
        return bankB2cOrderPayRequest;
    }

    @Override
    protected BizResponse callBizService(Object request) throws Exception {

        // 录入参数
        BankB2cOrderPayRequest bankB2cOrderPayRequest = (BankB2cOrderPayRequest) request;
        // 行号
        String instId = bankB2cOrderPayRequest.getHeader().getInstId();
        // 用户编号
        String userId = bankB2cOrderPayRequest.getUserId();

        /* 获取会话信息 */
        UserService userService = new UserServiceImpl();
        UserInfo userInfo = JSON.parseObject(RedisUtil.hashGet(bankB2cOrderPayRequest.getHeader().getSession(), bankB2cOrderPayRequest.getHeader().getInstId() + bankB2cOrderPayRequest.getUserId()), UserInfo.class);
        if (null == userInfo) {
            rglog.error("获取用户信息失败!");
            throw new BizException(RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespCode(), RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespDesc());
        }
        // 获取用户订单信息表
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();

        UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, bankB2cOrderPayRequest.getTxnNo());
        if (null == userOrderInfo) {
            rglog.debug("查询用户订单表异常");
            throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
        }
        /*登记支付备注*/
        userOrderInfo.setOrderDesc(bankB2cOrderPayRequest.getPayNotes());
        SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();
        List<SignAcctInfo> signList = signAcctInfoMapper.selectSignAcctInfoBySignToken(instId, bankB2cOrderPayRequest.getSignToken());
        /// 没有查询到签约账号
        if (signList == null || signList.size() == 0
                || !userId.equals(signList.get(0).getUserId())
                || AppParamConstant.NO.equals(signList.get(0).getSignStatus())) { // 签约状态正常
            rglog.debug("查询用户签约账号异常");
            throw new BizException(OltpRpcdEnum.RECOND_EMPTY_OR_NOT_FOUND.getRespCode(), OltpRpcdEnum.RECOND_EMPTY_OR_NOT_FOUND.getRespDesc());
        }

        // 主扫必须验证密码
        boolean checkResult = userService.checkUserPayPassword(instId, bankB2cOrderPayRequest.getUserId(), null, bankB2cOrderPayRequest.getPassword());
        if (!checkResult) {
            rglog.error("用户密码错误!");
            throw new BizException(RespCodeEnum.USER_PASSWORD_ERROR.getRespCode(), RespCodeEnum.USER_PASSWORD_ERROR.getRespDesc());
        }
        String limitInst = bankB2cOrderPayRequest.getHeader().getInstId() + "|" + userInfo.getUserInst() + "|" + bankB2cOrderPayRequest.getUserId();
        // 检查类型
        UserPayAuthTypeEnum userPayAuthTypeEnum = userService.getUserPayAuthType(instId, bankB2cOrderPayRequest.getUserId(), userOrderInfo.getOrderAmt(), LimitTypeEnum.CASHIER.getLimitType());
        String authType = userPayAuthTypeEnum.getType();
        // 02 密码+短信验证
        // 03 密码+软Ukey
        if ("02".equals(authType)) {
            // 验证短信验证码
            SmsService smsService = new SmsServiceImpl();
            smsService.verifySmsCode(bankB2cOrderPayRequest.getHeader().getInstId(), SmsTypeEnum.FAST_PAYMENT.getSmsType(),
                    bankB2cOrderPayRequest.getAuthCode(), bankB2cOrderPayRequest.getTransSeqNum());
        }

        SignAcctInfo signAcctInfo = signList.get(0);

        SysParamService sysParamService = new SysParamServiceImpl();
        /* 银联码，获取法人行在银联的机构号 */
        SysParam unionPayCode = sysParamService.getSysParamInfo(instId, "OPMS_SYS_PARAM", "unionPayerOrgCode" + "_" + bankB2cOrderPayRequest.getQddm());
        if (null == unionPayCode) {
            rglog.error("获取二维码服务失败！获取法人行在银联的机构号失败！instId:{}", instId);
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }

        // 银联机构号
        String strUnonPayCode = unionPayCode.getParamValue();

        // 查询银联优惠券
        queryCoupon(bankB2cOrderPayRequest, signAcctInfo, userOrderInfo, strUnonPayCode);

        //判断是否使用优惠券
        List<CouponInfoBean> couponInfoBeanList = null;
        //订单金额不为空时，校验订单表中的订单金额是否与交易金额一致
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getOrderAmt())
                && AmountUtil.compare(userOrderInfo.getOrderAmt(), bankB2cOrderPayRequest.getTxnAmt()) != 0) {
            rglog.error("支付金额和订单金额不一致！instId:{}， orderAmt:{}, txnAmt:{}", instId, userOrderInfo.getOrderAmt(), bankB2cOrderPayRequest.getTxnAmt());
            throw new BizException(RespCodeEnum.TRANS_AMT_DISACCORD.getRespCode(), RespCodeEnum.TRANS_AMT_DISACCORD.getRespDesc());
        }

        if (!StringUtil.isEmptyOrNull(userOrderInfo.getDiscountInfo())) {
            couponInfoBeanList = JSON.parseArray(userOrderInfo.getDiscountInfo(), CouponInfoBean.class);
        }

        //订单基恩
        userOrderInfo.setOrderAmt(AmountUtil.checkAmt(bankB2cOrderPayRequest.getTxnAmt(), 2, false, false));
        //需要支付金额
        userOrderInfo.setNeedPayAmt(AmountUtil.subtraction(bankB2cOrderPayRequest.getTxnAmt(), userOrderInfo.getRealDiscountAmt()));
        /*登记支付备注*/
        userOrderInfo.setOrderStatus(bankB2cOrderPayRequest.getPayNotes());

        B2COrderPayRequest b2COrderPayRequest = new B2COrderPayRequest();
        // 银联机构号
        b2COrderPayRequest.setIssInsCode(strUnonPayCode);
        // 订单金额	orderAmt
        b2COrderPayRequest.setOrderAmt(userOrderInfo.getRealPayAmt());
        // 交易币种
        b2COrderPayRequest.setOrderCcy(userOrderInfo.getOrderCcy());
        //交易顺序号	txnNo
        b2COrderPayRequest.setTxnNo(userOrderInfo.getSysSeqNum());
        //付款方信息	payerInfo
        PayerInfo payerInfo = new PayerInfo();

        // 付款人员信息
        // 本他行判断
        if ("0".equals(signAcctInfo.getSignAcctType().substring(0, 1))) {
            payerInfo.setAccNo(signAcctInfo.getSignAcctNo());
        } else {
            // 他行使用TOKEN
            payerInfo.setAccNo(signAcctInfo.getSignToken());
        }
        // card_hold_name
        payerInfo.setName(signAcctInfo.getCardHoldName());
        // 签约银行名称
        //payerInfo.setPayerBankInfo(signAcctInfo.getSignBankName());
        // 贷记卡判断
        // 01-本行贷记账户
        // 11-他行贷记账户
        if ("01".equals(signAcctInfo.getSignAcctType()) || "11".equals(signAcctInfo.getSignAcctType())) {
            payerInfo.setCardAttr("02"); // 贷记卡
        } else {
            payerInfo.setCardAttr("01"); // 借记卡
        }
        // 预留手机号
        payerInfo.setMobile(signAcctInfo.getReserveMobileNo());
        b2COrderPayRequest.setPayerInfo(payerInfo);

        //风控信息	riskInfo
        RiskInfoBean riskInfo = new RiskInfoBean();
        RiskInfo webRiskInfo = bankB2cOrderPayRequest.getRiskInfo();
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDevId())) {
            riskInfo.setDeviceID("DevId");
        } else {
            riskInfo.setDeviceID(webRiskInfo.getDevId());
        }
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDeviceMode())) {
            riskInfo.setDeviceName("DeviceMode");
        } else {
            riskInfo.setDeviceName(webRiskInfo.getDeviceMode());
        }
        if (StringUtil.isEmptyOrNull(webRiskInfo.getTermIp())) {
            riskInfo.setSourceIP("127.0.0.1");
        } else {
            riskInfo.setSourceIP(webRiskInfo.getTermIp());
        }
        riskInfo.setDeviceLocation(webRiskInfo.getDeviceLocation());
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDeviceMode())) {
            riskInfo.setDeviceType("DeviceType");
        } else {
            riskInfo.setDeviceType(webRiskInfo.getDeviceMode());
        }
        //应用提供方账户ID
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getUserId())) {
            riskInfo.setAccountIdHash(MD5Util.MD5Encode(signAcctInfo.getUserId()));
        }
        //银行预留手机号
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getReserveMobileNo())) {
            riskInfo.setMobile(signAcctInfo.getReserveMobileNo());
        }
        //账户注册日期  8 位日期字符 yyyymmdd
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getCreateTime())) {
            riskInfo.setUsrRgstrDt(DateUtil.dateStringFormatConvert(signAcctInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss.SSS", "yyyyMMdd"));
        }
        b2COrderPayRequest.setRiskInfoBean(riskInfo);

        // 付款方附言
        b2COrderPayRequest.setPayeeComments(bankB2cOrderPayRequest.getPayerComments());

        //使用you金劵
        if (couponInfoBeanList != null) {
            // 优惠金额
            b2COrderPayRequest.setOrigTxnAmt(userOrderInfo.getOrderAmt());
            // 银联返回的优惠信息
            b2COrderPayRequest.setCouponInfoList(couponInfoBeanList);
        }
        // 订单类型 一般消费
        //userOrderInfo.setOrderType("10");

        cc.rengu.igas.channel.upqc.facade.base.Header upHeader = new cc.rengu.igas.channel.upqc.facade.base.Header();
        BeanUtil.beanCopy(bankB2cOrderPayRequest.getHeader(), upHeader);
        upHeader.setTxnNum("0130000903");// 付款
        upHeader.setSrcSysId("OPMS");
        b2COrderPayRequest.setHeader(upHeader);
        b2COrderPayRequest.setOrderType("10");
        // 实际支付金额
        b2COrderPayRequest.setOrderAmt(userOrderInfo.getRealPayAmt());

        // 调用银联付款
        DubboService dubboService = new DubboServiceImpl();
        Result<B2COrderPayResponse> responseResult = (Result<B2COrderPayResponse>) dubboService.callDubboService("upqcPayerService", "b2cOrderPay", b2COrderPayRequest);
        if (null == responseResult || !responseResult.isSuccess()) {
            rglog.error("调用银联主扫二维码付款，订单号<{}>失败", bankB2cOrderPayRequest.getTxnNo());
            throw new BizException(RespCodeEnum.B2C_PAY_ERR.getRespCode(), RespCodeEnum.B2C_PAY_ERR.getRespDesc());
        }
        if (!CopsParamConstant.DUBBO_SUCCESS.equals(responseResult.getResult().getRespCode())) {
            rglog.error("调用银联主扫二维码付款，订单号<{}>信息失败,iReturnCode:<{}>",
                    bankB2cOrderPayRequest.getTxnNo(),
                    responseResult.getResult().getRespCode());
            throw new BizException(responseResult.getResult().getRespCode(), responseResult.getResult().getRespDesc());
        }

        B2COrderPayResponse orderPayResponse = responseResult.getResult();

        // 业务状态
        // 非正常状态更新失败
        if (!"00000000".equals(orderPayResponse.getRespCode())) {
            // 更新为失败
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            rglog.error("支付失败，sysSeqNum:<{}>, dubboRespCode:<{}> !", userOrderInfo.getSysSeqNum(), orderPayResponse.getRespCode());
        } else {
            // 更新为成功
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            /*累计用户限额*/
            userService.updateUserTransLimit(userOrderInfo.getInstId(),
                    signAcctInfo.getUserId(),
                    "P01PM004",
                    userOrderInfo.getRealPayAmt());
        }
        // 付款信息
        userOrderInfo.setFrontSeqNum(orderPayResponse.getVoucherNum());
        // 用户编号
        userOrderInfo.setUserId(signAcctInfo.getUserId());

        //增加付款人信息
        JSONObject josnObj = new JSONObject();
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getOrderExtraInfo())) {
            josnObj = JSON.parseObject(userOrderInfo.getOrderExtraInfo());
        }
        if (AcctTypeEnum.BANK_CREDIT.getAcctType().equals(signAcctInfo.getSignAcctType())
                || AcctTypeEnum.BANK_DEBIT.getAcctType().equals(signAcctInfo.getSignAcctType())) {
            josnObj.put("payType", PayTypeEnum.BANK_CARD.getPayType());
        } else if (AcctTypeEnum.OTHER_CREDIT.getAcctType().equals(signAcctInfo.getSignAcctType())
                || AcctTypeEnum.OTHER_DEBIT.getAcctType().equals(signAcctInfo.getSignAcctType())) {
            josnObj.put("payType", PayTypeEnum.OTHER_BANK_CARD.getPayType());
        }
        josnObj.put("payerAcctInfo", signAcctInfo.getSignAcctNo());
        josnObj.put("payerAcctName", signAcctInfo.getCardHoldName());
        josnObj.put("payerAcctType", signAcctInfo.getSignAcctType());
        josnObj.put("transFlag", "0");//支付
        userOrderInfo.setOrderExtraInfo(JSON.toJSONString(josnObj));

        OrderService orderService = new OrderServiceImpl();
        // 更新状态
        boolean isOrderCode = orderService.updateOrderInfo(userOrderInfo, null, null);
        if (!isOrderCode) {
            rglog.error("更新用户订单表失败!");
            throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
        }

        BankB2cOrderPayResponse bankB2cOrderPayResponse = new BankB2cOrderPayResponse();
        bankB2cOrderPayResponse.setRespCode(orderPayResponse.getRespCode());
        bankB2cOrderPayResponse.setRespDesc(orderPayResponse.getRespDesc());

        // 实际支付金额
        bankB2cOrderPayResponse.setActualAmt(userOrderInfo.getRealPayAmt());
        // 优惠金额
        bankB2cOrderPayResponse.setDiscountAmt(userOrderInfo.getRealDiscountAmt());
        // 订单金额
        bankB2cOrderPayResponse.setOrderAmt(userOrderInfo.getOrderAmt());
        // 存在优惠
        if (couponInfoBeanList != null && couponInfoBeanList.size() != 0) {
            CouponInfo opmscoupBean = new CouponInfo();
            BeanUtil.beanCopy(couponInfoBeanList.get(0), opmscoupBean);
            bankB2cOrderPayResponse.setCouponInfo(opmscoupBean);
        }

        BizResponse bizResponse = new BizResponse();
        // 返回
        bizResponse.setResult(bankB2cOrderPayResponse);// 返回结果
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        if (!"00".equals(orderPayResponse.getRespCode())) {
            bizResponse.setRespCode(orderPayResponse.getRespCode());
            bizResponse.setRespDesc(orderPayResponse.getRespDesc());
        }
        return bizResponse;
    }

    @Override
    protected void afterBizProcess(BizResponse response) throws Exception {
        BankB2cOrderPayResponse retResponse = (BankB2cOrderPayResponse) response.getResult();
        ConvertUtil.convertInput(retResponse);
    }

    @Override
    protected RiskMonitorInfo getRiskMonitorInfo() {
        return null;
    }

    /**
     * 查询营销，确认银联是否有优惠
     */
    private void queryCoupon(BankB2cOrderPayRequest bankB2cOrderPayRequest,
                             SignAcctInfo signAcctInfo,
                             UserOrderInfo userOrderInfo,
                             String strUnonPayCode) throws Exception {
        rglog.debug("开始查询银联营销{}", userOrderInfo.getSysSeqNum());
        B2CQueryCouponRequest b2CQueryCouponRequest = new B2CQueryCouponRequest();

        PayerInfo payerInfo = new PayerInfo();

        // 付款人员信息
        // 本他行判断
        if ("0".equals(signAcctInfo.getSignAcctType().substring(0, 1))) {
            payerInfo.setAccNo(signAcctInfo.getSignAcctNo());
        } else {
            // 他行使用TOKEN
            payerInfo.setAccNo(signAcctInfo.getSignToken());
        }
        // card_hold_name
        payerInfo.setName(signAcctInfo.getCardHoldName());
        // 签约银行名称
        //payerInfo.setPayerBankInfo(signAcctInfo.getSignBankName());
        // 贷记卡判断
        // 01-本行贷记账户
        // 11-他行贷记账户
        if ("01".equals(signAcctInfo.getSignAcctType()) || "11".equals(signAcctInfo.getSignAcctType())) {
            payerInfo.setCardAttr("02"); // 贷记卡
        } else {
            payerInfo.setCardAttr("01"); // 借记卡
        }
        // 预留手机号
        payerInfo.setMobile(signAcctInfo.getReserveMobileNo());
        b2CQueryCouponRequest.setPayerInfo(payerInfo);

        // 银联机构号
        b2CQueryCouponRequest.setIssInsCode(strUnonPayCode);
        // 订单金额	orderAmt --与页面交互，无需除以100
        b2CQueryCouponRequest.setOrderAmt(bankB2cOrderPayRequest.getTxnAmt());
        //交易顺序号	txnNo
        b2CQueryCouponRequest.setTxnNo(userOrderInfo.getSysSeqNum());

        // 收款方信息	payeeInfoBean
        PayeeInfoBean payeeInfoBean = JSON.parseObject(userOrderInfo.getRemark2(), PayeeInfoBean.class);
        b2CQueryCouponRequest.setPayeeInfoBean(payeeInfoBean);

        //风控信息	riskInfo
        RiskInfoBean riskInfo = new RiskInfoBean();
        RiskInfo webRiskInfo = bankB2cOrderPayRequest.getRiskInfo();
        riskInfo.setDeviceID(webRiskInfo.getDevId());
        riskInfo.setDeviceName(webRiskInfo.getDeviceMode());
        riskInfo.setSourceIP(webRiskInfo.getTermIp());
        riskInfo.setDeviceLocation(webRiskInfo.getDeviceLocation());
        riskInfo.setDeviceType(webRiskInfo.getDeviceMode());
        //风控信息	riskInfo
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDevId())) {
            riskInfo.setDeviceID("DevId");
        } else {
            riskInfo.setDeviceID(webRiskInfo.getDevId());
        }
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDeviceMode())) {
            riskInfo.setDeviceName("DeviceMode");
        } else {
            riskInfo.setDeviceName(webRiskInfo.getDeviceMode());
        }
        if (StringUtil.isEmptyOrNull(webRiskInfo.getTermIp())) {
            riskInfo.setSourceIP("127.0.0.1");
        } else {
            riskInfo.setSourceIP(webRiskInfo.getTermIp());
        }
        riskInfo.setDeviceLocation(webRiskInfo.getDeviceLocation());
        if (StringUtil.isEmptyOrNull(webRiskInfo.getDeviceMode())) {
            riskInfo.setDeviceType("DeviceType");
        } else {
            riskInfo.setDeviceType(webRiskInfo.getDeviceMode());
        }
        //应用提供方账户ID
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getUserId())) {
            riskInfo.setAccountIdHash(MD5Util.MD5Encode(signAcctInfo.getUserId()));
        }
        //银行预留手机号
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getReserveMobileNo())) {
            riskInfo.setMobile(signAcctInfo.getReserveMobileNo());
        }
        //账户注册日期  8 位日期字符 yyyymmdd
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getCreateTime())) {
            riskInfo.setUsrRgstrDt(DateUtil.dateStringFormatConvert(signAcctInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss.SSS", "yyyyMMdd"));
        }

        b2CQueryCouponRequest.setRiskInfo(riskInfo);

        cc.rengu.igas.channel.upqc.facade.base.Header upHeader = new cc.rengu.igas.channel.upqc.facade.base.Header();
        BeanUtil.beanCopy(bankB2cOrderPayRequest.getHeader(), upHeader);
        upHeader.setTxnNum("0180000903");// 查询营销
        upHeader.setSrcSysId("OPMS");
        b2CQueryCouponRequest.setHeader(upHeader);
        b2CQueryCouponRequest.setOrderCcy("156");
        // 查询营销
        DubboService dubboService = new DubboServiceImpl();
        Result<B2CQueryCouponResponse> responseResult = (Result<B2CQueryCouponResponse>) dubboService.callDubboService("upqcPayerService",
                "b2cQueryCoupon", b2CQueryCouponRequest);

        // 计算优惠金额
        String couponAmt = "0";
        List<CouponInfo> couponInfoList = new ArrayList<CouponInfo>();
        if (null != responseResult.getResult().getCouponInfoList()
                && responseResult.getResult().getCouponInfoList().size() != 0) {
            for (CouponInfoBean couponInfoBean : responseResult.getResult().getCouponInfoList()) {
                // 优惠累加
                couponAmt = AmountUtil.addition(couponAmt, couponInfoBean.getOffstAmt());
                // 复制Bean
                CouponInfo reCouBean = new CouponInfo();
                BeanUtil.beanCopy(couponInfoBean, reCouBean);
                couponInfoList.add(reCouBean);
            }
        }

        // 没有金额模式
        if (StringUtil.isEmptyOrNull(userOrderInfo.getOrderAmt())) {
            // 交易金额
            userOrderInfo.setOrderAmt(bankB2cOrderPayRequest.getTxnAmt());
        }
        // 实际支付金额
        userOrderInfo.setRealPayAmt(AmountUtil.subtraction(userOrderInfo.getOrderAmt(), couponAmt));
        // 实际优惠总金额
        userOrderInfo.setRealDiscountAmt(couponAmt);
        // 有优惠
        if (responseResult.getResult().getCouponInfoList() != null) {
            // 优惠信息列表
            userOrderInfo.setDiscountInfo(JSON.toJSONString(responseResult.getResult().getCouponInfoList()));
        }
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        return null;
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        return null;
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        return null;
    }
}
